using System;
using System.Linq;
using System.Threading.Tasks;
using mymvc_individual.Models;
using mymvc_individual.Data;
using Microsoft.EntityFrameworkCore;

namespace mymvc_individual.Services
{
    public class TodoItemService : ITodoItemService
    {
        private readonly ApplicationDbContext _dbContext;

        public TodoItemService(ApplicationDbContext dbContext)
        {
            _dbContext = dbContext;
        }

        public async Task<TodoItem[]> GetIncompleteItemsAsync(ApplicationUser user)
        {
            var items = await _dbContext.Items
                .Where(x => x.UserId == user.Id)
                .ToArrayAsync();

            return items;
        }

        public async Task<bool> AddItemAsync(TodoItem newItem, ApplicationUser user)
        {
            newItem.Id = new Guid();
            newItem.IsDone = false;
            newItem.DueAt = DateTimeOffset.Now.AddHours(3);
            newItem.UserId = user.Id;

            _dbContext.Items.Add(newItem);

            var result = await _dbContext.SaveChangesAsync();

            return result == 1;
        }

        public async Task<bool> DeleteItemAsync(string title, ApplicationUser user)
        {
            var items = _dbContext.Items
                .Where(x => x.Title == title && x.UserId == user.Id);

            _dbContext.Items.RemoveRange(items);

            var result = await _dbContext.SaveChangesAsync();

            return result > 0;
        }

        public async Task<bool> MarkDoneAsync(Guid id, ApplicationUser user)
        {
            var item = await _dbContext.Items
                .Where(x => x.Id == id && x.UserId == user.Id).SingleOrDefaultAsync();

            if (item == null) return false;

            item.IsDone = !item.IsDone;
            var result = await _dbContext.SaveChangesAsync();

            return result > 0;
        }

        public async Task<bool> ModifyItemAsync(Guid id, TodoItem newItem, ApplicationUser user)
        {
            var item = await _dbContext.Items
                .Where(x => x.Id == id && x.UserId == user.Id).SingleOrDefaultAsync();

            if (item == null) return false;

            item.Title = newItem.Title;
            item.IsDone = newItem.IsDone;
            item.DueAt = newItem.DueAt;

            var result = await _dbContext.SaveChangesAsync();

            return result == 1;
        }
    }
}